package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.user.wechatuser.*;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.service.user.WechatUserService;
import com.uzai.console.service.user.WechatUserSyncService;
import com.uzai.console.vo.smscode.SmsCodeVo;
import com.uzai.console.vo.user.wechatuser.MinMaxCreateTimeVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/***
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WechatUserSyncServiceImpl implements WechatUserSyncService {

    Logger logger = LoggerFactory.getLogger(WechatUserSyncServiceImpl.class);

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private DyOrderMapper dyOrderMapper;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

    /**
     * 查询结果添加群发任务
     *
     * @param wechatUserBatchSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void  sendMessageToUserSelectedSync(WechatUserBatchSendMsgDto wechatUserBatchSendMsgDto){

        //记录发送总数
        int totalCount_parent_succ = 0;

        WechatUserQuery wechatUserQuery = wechatUserBatchSendMsgDto.getWechatUserQuery();
        wechatUserQuery.setMerId(wechatUserBatchSendMsgDto.getMerId());
        //查询条件中是否包含机器人id,
        if(wechatUserQuery.getDeviceUniqueId() != null ) {//条件中带机器人id,则添加到机器人列表中
            int totalCount_son_succ = wechatUserService.groupSendMsgByDeviceUniqueId(wechatUserBatchSendMsgDto);
            totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
        }else if(wechatUserQuery.getDeviceUniqueIdList() != null && wechatUserQuery.getDeviceUniqueIdList().size() > 0){
            List<Long> deviceUniqueIdList = wechatUserQuery.getDeviceUniqueIdList();
            for(Long devieUniqueId : deviceUniqueIdList){
                try {
                    WechatUserBatchSendMsgDto wechatUserBatchSendMsgDto_deviceUniqueId = new WechatUserBatchSendMsgDto();
                    wechatUserBatchSendMsgDto_deviceUniqueId.setMerId(wechatUserBatchSendMsgDto.getMerId());
                    wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserGroupSendMsgDto(wechatUserBatchSendMsgDto.getWechatUserGroupSendMsgDto());
                    wechatUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParentId(wechatUserBatchSendMsgDto.getGroupSendJobParentId());
                    WechatUserQuery wechatUserQuery_deviceUniqueId = new WechatUserQuery();
                    BeanUtils.copyProperties(wechatUserQuery, wechatUserQuery_deviceUniqueId);
                    wechatUserQuery_deviceUniqueId.setDeviceUniqueId(devieUniqueId);
                    wechatUserQuery_deviceUniqueId.setDeviceUniqueIdList(null);
                    wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserQuery(wechatUserQuery_deviceUniqueId);
                    int totalCount_son_succ = wechatUserService.groupSendMsgByDeviceUniqueId(wechatUserBatchSendMsgDto_deviceUniqueId);
                    totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                }catch (Exception e){
                    logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", wechatUserQuery.getDeviceUniqueId(), e.getMessage());
                }
            }
        }else{//如果没有，则查询该运营商所有的机器人
            DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
            deviceWechatInfoQuery.setMerId(wechatUserBatchSendMsgDto.getMerId());
            List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
            if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
                for(DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList){
                    try{
                        WechatUserBatchSendMsgDto wechatUserBatchSendMsgDto_deviceUniqueId = new WechatUserBatchSendMsgDto();
                        wechatUserBatchSendMsgDto_deviceUniqueId.setMerId(wechatUserBatchSendMsgDto.getMerId());
                        wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserGroupSendMsgDto(wechatUserBatchSendMsgDto.getWechatUserGroupSendMsgDto());
                        wechatUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParentId(wechatUserBatchSendMsgDto.getGroupSendJobParentId());
                        WechatUserQuery wechatUserQuery_deviceUniqueId = new WechatUserQuery();
                        BeanUtils.copyProperties(wechatUserQuery, wechatUserQuery_deviceUniqueId);
                        wechatUserQuery_deviceUniqueId.setMerId(wechatUserBatchSendMsgDto.getMerId());
                        wechatUserQuery_deviceUniqueId.setDeviceUniqueId(deviceWechatInfo.getId());
                        wechatUserQuery_deviceUniqueId.setDeviceUniqueIdList(null);
                        wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserQuery(wechatUserQuery_deviceUniqueId);
                        int totalCount_son_succ = wechatUserService.groupSendMsgByDeviceUniqueId(wechatUserBatchSendMsgDto_deviceUniqueId);
                        totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                    }catch (Exception e){
                        logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", wechatUserQuery.getDeviceUniqueId(), e.getMessage());
                    }
                }
            }
        }

        //全部执行完成之后，修改主任务状态
        if(wechatUserBatchSendMsgDto.getGroupSendJobParentId() != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(wechatUserBatchSendMsgDto.getGroupSendJobParentId(), wechatUserBatchSendMsgDto.getMerId());
            if(groupSendJob != null){
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue()); //将状态设置为未开始状态
                groupSendJob.setTotalCount(totalCount_parent_succ);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), wechatUserBatchSendMsgDto.getGroupSendJobParentId(), wechatUserBatchSendMsgDto.getMerId());
            }
        }
    }

    /**
     * 多选框选择会员添加群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserSendMsgBatchDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void sendMessageToUserBatchSync(WechatUserSendMsgBatchDto wechatUserSendMsgBatchDto){
        //记录发送总数
        int totalCount_parent_succ = 0;
        //查询该运营商所有得机器人
        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
        deviceWechatInfoQuery.setMerId(wechatUserSendMsgBatchDto.getMerId());
        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
            for(DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList){
                try{
                    WechatUserSendMsgBatchDto wechatUserSendMsgBatchDto_deviceUniqueId = new WechatUserSendMsgBatchDto();
                    wechatUserSendMsgBatchDto_deviceUniqueId.setMerId(wechatUserSendMsgBatchDto.getMerId());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setWechatUserGroupSendMsgDto(wechatUserSendMsgBatchDto.getWechatUserGroupSendMsgDto());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setGroupSendJobParentId(wechatUserSendMsgBatchDto.getGroupSendJobParentId());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setDeviceUniqueId(deviceWechatInfo.getId());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setIdList(wechatUserSendMsgBatchDto.getIdList());
                    int totalCount_son_succ = wechatUserService.groupSendMsgByDeviceUniqueIdBatch(wechatUserSendMsgBatchDto_deviceUniqueId);
                    totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                }catch (Exception e){
                    logger.error("-------sendMessageToUserBatchSync is error; deviceUniqueId={}, error={}", deviceWechatInfo.getId(), e.getMessage());
                }
            }
        }

        //全部执行完成之后，修改主任务状态
        if(wechatUserSendMsgBatchDto.getGroupSendJobParentId() != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(wechatUserSendMsgBatchDto.getGroupSendJobParentId(), wechatUserSendMsgBatchDto.getMerId());
            if(groupSendJob != null){
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue()); //将状态设置为未开始状态
                groupSendJob.setTotalCount(totalCount_parent_succ);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), wechatUserSendMsgBatchDto.getGroupSendJobParentId(), wechatUserSendMsgBatchDto.getMerId());
            }
        }
    }

    /**
     * 查询结果定投筛选
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserBatchOptCpcDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void optCpcToUserSelected(WechatUserBatchOptCpcDto wechatUserBatchOptCpcDto){
        if(wechatUserBatchOptCpcDto.getMerId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUserOptCpcDto wechatUserOptCpcDto =  wechatUserBatchOptCpcDto.getWechatUserOptCpcDto();
        if(wechatUserOptCpcDto == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(wechatUserOptCpcDto.getCpaId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
        }

        Page<WechatUser> page = new Page<>();
        page.setSize(10);
        page.setCurrent(1);
//        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserBatchOptCpcDto.getWechatUserQuery());
//        while (wechatUserList != null && wechatUserList.size() > 0){
//            for (WechatUser wechatUser : wechatUserList){
//                wechatUserOptCpcDto.setId(wechatUser.getId());
//                wechatUserService.optCpcToOneUser(wechatUserOptCpcDto);
//            }
//            //每次查询第一页
//            wechatUserList = wechatUserMapper.findByList(page, wechatUserBatchOptCpcDto.getWechatUserQuery());
//        }
    }

    /**
     * 查询结果批量修改
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserBatchUpdateDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserSelected(WechatUserBatchUpdateDto wechatUserBatchUpdateDto){

        if(wechatUserBatchUpdateDto.getMerId() == null ){
            return;
        }

        if(wechatUserBatchUpdateDto.getWechatUserUpdateDto() == null){
            return;
        }

        WechatUserQuery wechatUserQuery = wechatUserBatchUpdateDto.getWechatUserQuery();
        wechatUserQuery.setMerId(wechatUserBatchUpdateDto.getMerId());
        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WechatUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                if(wechatUserList != null && wechatUserList.size() > 0){
                    for(WechatUser wechatUser : wechatUserList) {
                        try {
                            WechatUserUpdateDto wechatUserUpdateDto = new WechatUserUpdateDto();
                            //赋值
                            BeanUtils.copyProperties(wechatUserBatchUpdateDto.getWechatUserUpdateDto(), wechatUserUpdateDto);
                            wechatUserUpdateDto.setMerId(wechatUserBatchUpdateDto.getMerId());
                            wechatUserUpdateDto.setId(wechatUser.getId());
                            wechatUserUpdateDto.setLoginToken(wechatUserBatchUpdateDto.getLoginToken());
                            wechatUserService.updateToOneUser(wechatUserUpdateDto);

                            //营销奖励黑名单
                            //marketingRewardsBlackListService.addOrRemoveByFlag(wechatUser.getMerId(), String.valueOf(wechatUser.getId()), wechatUserUpdateDto.getMarketingRewardsBlackListRemark(), wechatUserUpdateDto.getMarketingRewardsBlackListFlag());
                        } catch (Exception e) {
                            logger.error("-------updateToOneUser is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        MinMaxCreateTimeVo minMaxCreateTimeVo = wechatUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
//        //有总数，且最小创建时间有
//        if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询10天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页200个
//                    Page<WechatUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
//                    while (wechatUserList != null && wechatUserList.size() > 0){
//                        for(WechatUser wechatUser : wechatUserList) {
//                            try {
//                                WechatUserUpdateDto wechatUserUpdateDto = new WechatUserUpdateDto();
//                                //赋值
//                                BeanUtils.copyProperties(wechatUserBatchUpdateDto.getWechatUserUpdateDto(), wechatUserUpdateDto);
//                                wechatUserUpdateDto.setMerId(wechatUserBatchUpdateDto.getMerId());
//                                wechatUserUpdateDto.setId(wechatUser.getId());
//                                wechatUserService.updateToOneUser(wechatUserUpdateDto);
//                            } catch (Exception e) {
//                                logger.error("-------updateToOneUser is error userId={}, error={}", wechatUser.getId(), e.getMessage());
//                            }
//                            WechatUserUpdateDto wechatUserUpdateDto = wechatUserBatchUpdateDto.getWechatUserUpdateDto();
//                            marketingRewardsBlackListService.addOrRemoveByFlag(wechatUser.getMerId(), wechatUser.getBizUserId(), wechatUserUpdateDto.getMarketingRewardsBlackListRemark(), wechatUserUpdateDto.getMarketingRewardsBlackListFlag());
//                        }
//
//                        //再次查询下一页
//                        current ++;
//                        page.setCurrent(current);
//                        wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
//                    }
//                }
//            }
//        }
    }


    /**
     * 批量修改（多选框选择会员）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserUpdateBatchDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserBatch(WechatUserUpdateBatchDto wechatUserUpdateBatchDto){
        if(wechatUserUpdateBatchDto.getMerId() == null ){
            return;
        }

        if(wechatUserUpdateBatchDto.getWechatUserUpdateDto() == null){
            return;
        }

        List<Long> idList = wechatUserUpdateBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            return;
        }

        if(idList != null && idList.size() > 0){
            //查询所有机器人
            for(Long id : idList){
                try{
                    WechatUserUpdateDto wechatUserUpdateDto = new WechatUserUpdateDto();
                    //赋值
                    BeanUtils.copyProperties(wechatUserUpdateBatchDto.getWechatUserUpdateDto(), wechatUserUpdateDto);
                    wechatUserUpdateDto.setMerId(wechatUserUpdateBatchDto.getMerId());
                    wechatUserUpdateDto.setId(id);
                    wechatUserUpdateDto.setLoginToken(wechatUserUpdateBatchDto.getLoginToken());
                    wechatUserService.updateToOneUser(wechatUserUpdateDto);
                }catch (Exception e){
                    logger.error("-------updateToOneUser is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 删除所有查询的会员数据
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserBatchDeleteDto
     * @return null
     */
    public void deleteUserSelected(WechatUserBatchDeleteDto wechatUserBatchDeleteDto){

        Long merId = wechatUserBatchDeleteDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getWechatUserDelByQuery() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if(smsCodeFlag){
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserBatchDeleteDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wechatUserBatchDeleteDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserBatchDeleteDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            }
        }

        WechatUserQuery wechatUserQuery = wechatUserBatchDeleteDto.getWechatUserQuery();
        wechatUserQuery.setMerId(wechatUserBatchDeleteDto.getMerId());

        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WechatUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                if(wechatUserList != null && wechatUserList.size() > 0){
                    for(WechatUser wechatUser : wechatUserList) {
                        try{
                            wechatUserService.deleteUserById(wechatUser.getId(), wechatUserQuery.getMerId());
                        }catch (Exception e){
                            logger.error("-------deleteUserById is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        MinMaxCreateTimeVo minMaxCreateTimeVo = wechatUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
//        //有总数，且最小创建时间有
//        if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询5天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页200个
//                    Page<WechatUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
//                    while (wechatUserList != null && wechatUserList.size() > 0){
//                        for (WechatUser wechatUser : wechatUserList){
//                            try{
//                                wechatUserService.deleteUserById(wechatUser.getId(), wechatUserQuery.getMerId());
//                            }catch (Exception e){
//                                logger.error("-------deleteUserById is error userId={}, error={}", wechatUser.getId(), e.getMessage());
//                            }
//                        }
//                        wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
//                    }
//                }
//            }
//        }
    }

    /**
     * 批量删除会员数据（多选框）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserIdListDto
     * @return null
     */
    public void deleteUserBatch(WechatUserIdListDto wechatUserIdListDto){

        Long merId = wechatUserIdListDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getWechatUserDelBySelected() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if(smsCodeFlag){
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserIdListDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(wechatUserIdListDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(wechatUserIdListDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            }
        }

        //封装批量删除的用户ID
        List<Long> idList = wechatUserIdListDto.getIdList();
        if(wechatUserIdListDto.getIdList() != null && wechatUserIdListDto.getIdList().size() > 0){
            for (Long id : idList){
                try {
                    wechatUserService.deleteUserById(id, wechatUserIdListDto.getMerId());
                }catch (Exception e){
                    logger.error("-------deleteUserById is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 批量删除下级会员数据（多选框）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserDeleteSonBatchDto
     * @return null
     */
    public void deleteSonWechatUserBatch(WechatUserDeleteSonBatchDto wechatUserDeleteSonBatchDto){

        if(wechatUserDeleteSonBatchDto.getIdentity() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "身份参数不能为空");
        }

        //封装批量删除的用户ID
        List<Long> idList = wechatUserDeleteSonBatchDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择需要删除的下级成员");
        }

        for (Long id : idList){
            try {
                WechatUserDeleteSonDto wechatUserDeleteSonDto = new WechatUserDeleteSonDto();
                BeanUtils.copyProperties(wechatUserDeleteSonBatchDto, wechatUserDeleteSonDto);
                wechatUserDeleteSonDto.setId(id);
                wechatUserDeleteSonDto.setIdentity(wechatUserDeleteSonBatchDto.getIdentity());
                wechatUserDeleteSonDto.setMerId(wechatUserDeleteSonBatchDto.getMerId());
                wechatUserService.deleteSonWechatUser(wechatUserDeleteSonDto);
            }catch (Exception e){
                logger.error("-------deleteSonWechatUser is error userId={}, error={}", id, e.getMessage());
            }
        }
    }

    /**
     * 异步修改个人微信默认客户端
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param batchUpdateDefaultClientDto
     * @return null
     */
    @Async("taskExecutor")
    public void updateDefaultClientSync(BatchUpdateDefaultClientDto batchUpdateDefaultClientDto){
        Long merId = batchUpdateDefaultClientDto.getMerId();
        if(merId == null){
            return;
        }

        Long deviceUniqueIdOld = batchUpdateDefaultClientDto.getDeviceUniqueIdOld();
        if(deviceUniqueIdOld == null ){
            return;
        }

        Long deviceUniqueIdNew = batchUpdateDefaultClientDto.getDeviceUniqueIdNew();
        if(deviceUniqueIdNew == null ){
            return;
        }

        List<Long> userTypeIdOldList = batchUpdateDefaultClientDto.getUserTypeIdOldList();

        if(userTypeIdOldList == null || userTypeIdOldList.size() == 0){
            return;
        }

        List<Long> userTypeIdNewList = batchUpdateDefaultClientDto.getUserTypeIdNewList();
        if(userTypeIdNewList == null || userTypeIdNewList.size() == 0){
            return;
        }

        //是否转移订单默认客户端
        Integer transferDataFlag =  batchUpdateDefaultClientDto.getTransferDataFlag();
        if(Tools.getInteger(transferDataFlag).intValue() == 1){ //转移订单的默认客户端
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        }


        //新的会员类型列表长度必须大于旧的会员类型列表长度
        if(userTypeIdNewList.size() < userTypeIdOldList.size()){
            return;
        }

        for(int i=0; i<userTypeIdOldList.size(); i++){

            Long userTypeIdOld = userTypeIdOldList.get(i);
            UserType userTypeOld = userTypeMapper.selectById(userTypeIdOld, merId);
            if(userTypeOld == null){
                continue;
            }

            Long userTypeIdNew = userTypeIdNewList.get(i);
            UserType userTypeNew = userTypeMapper.selectById(userTypeIdNew, merId);
            if(userTypeNew == null){
                continue;
            }

            //身份不一样，则跳过不修改
            if(Tools.getInteger(userTypeOld.getIdentity()).intValue() != Tools.getInteger(userTypeNew.getIdentity()).intValue()){
                continue;
            }

            //修改会员默认客户端
            UpdateDefaultClient updateDefaultClient  = new UpdateDefaultClient();
            updateDefaultClient.setMerId(merId);
            updateDefaultClient.setDeviceUniqueIdOld(deviceUniqueIdOld);
            updateDefaultClient.setDeviceUniqueIdNew(deviceUniqueIdNew);
            updateDefaultClient.setUserTypeIdOld(userTypeIdOld);
            updateDefaultClient.setUserTypeIdNew(userTypeIdNew);
            wechatUserMapper.updateDefaultClient(updateDefaultClient);
        }
    }

    /**
     * 查询结果批量修改营销奖励信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserUpdateMarketingRewardByQueryResultDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void updateMarketingRewardByQueryResult(WechatUserUpdateMarketingRewardByQueryResultDto wechatUserUpdateMarketingRewardByQueryResultDto){

        if(wechatUserUpdateMarketingRewardByQueryResultDto.getMerId() == null ){
            return;
        }

        if(wechatUserUpdateMarketingRewardByQueryResultDto.getMarketingReward() == null){
            return;
        }

        WechatUserQuery wechatUserQuery = wechatUserUpdateMarketingRewardByQueryResultDto.getWechatUserQuery();
        wechatUserQuery.setMerId(wechatUserUpdateMarketingRewardByQueryResultDto.getMerId());
        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);

        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WechatUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                if(wechatUserList != null && wechatUserList.size() > 0){
                    for(WechatUser wechatUser : wechatUserList) {
                        try {
                            UpdateMarketingRewardDto updateMarketingRewardDto = new UpdateMarketingRewardDto();
                            //赋值
                            BeanUtils.copyProperties(wechatUserUpdateMarketingRewardByQueryResultDto.getMarketingReward(), updateMarketingRewardDto);
                            updateMarketingRewardDto.setMerId(wechatUserUpdateMarketingRewardByQueryResultDto.getMerId());
                            updateMarketingRewardDto.setId(wechatUser.getId());
                            updateMarketingRewardDto.setMarketingReward(wechatUserUpdateMarketingRewardByQueryResultDto.getMarketingReward());
                            wechatUserService.updateMarketingReward(updateMarketingRewardDto);
                        } catch (Exception e) {
                            logger.error("-------updateMarketingReward is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
    }

}
